package com.wanxi.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanxi.dto.Constant;
import com.wanxi.mapper.LawyerMapper;
import com.wanxi.model.LawyerModel;
import com.wanxi.service.LawyerService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.ml.EvaluateDataFrameRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Li
 * @Date 2023/7/7 19:56
 */
@Service
public class LawyerServiceImpl extends ServiceImpl<LawyerMapper, LawyerModel> implements LawyerService {
    private static Logger logger = LoggerFactory.getLogger(LawyerServiceImpl.class.getName());
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public void addDocument(LawyerModel lawyerModel) throws IOException {
        //		创建请求
        IndexRequest request = new IndexRequest(Constant.ES_INDEX);
//		规则 put /lawyer_index/_doc/1
        Long eid = lawyerModel.getId();
        request.id(String.valueOf(eid));
        request.timeout("1s");
//		将数据放入请求 以JSON格式
        IndexRequest source = request.source(JSON.toJSONString(lawyerModel), XContentType.JSON);
//		客户端发送请求,获取响应的结果
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        logger.info(indexResponse.toString());
        logger.info(String.valueOf(indexResponse.status()));

    }

    @Override
    public void deleteDocument(LawyerModel lawyerModel) throws IOException {

        Long eid = lawyerModel.getId();
        DeleteRequest deleteRequest = new DeleteRequest(Constant.ES_INDEX, String.valueOf(eid));
        deleteRequest.timeout("1s");
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        logger.info(String.valueOf(delete));

    }

    @Override
    public void updateDocument(LawyerModel lawyerModel) throws IOException {
        Long eid = lawyerModel.getId();
        UpdateRequest updateRequest = new UpdateRequest(Constant.ES_INDEX, String.valueOf(eid));
        updateRequest.timeout("1s");
        updateRequest.doc(JSON.toJSONString(lawyerModel), XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        logger.info(String.valueOf(update));
    }

    @Override
    public List<Map<String, Object>> searchLawyer(LawyerModel lawyerModel) throws IOException {
        int pageNu = lawyerModel.getPage();
        int pageSize = lawyerModel.getLimit()*5;
        int from = (pageNu-1)*pageSize;

        SearchRequest searchRequest = new SearchRequest(Constant.ES_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.from(from);
        searchSourceBuilder.size(pageSize);
//查询
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("introduce", lawyerModel.getIntroduce());
        searchSourceBuilder.query(matchPhraseQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //实现搜索高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("introduce");
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);
//执行查询
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(search.getHits()));
//        解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : search.getHits().getHits()) {
//            获取高亮字段
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField introduce = highlightFields.get("introduce");

//            原来的查询数据
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
//            解析高亮的字段，进行高亮替换
            if (introduce != null) {
                Text[] fragments = introduce.fragments();
                String n_introduce = "";
                for (Text text : fragments) {
                    n_introduce += text;
                }
//    将原来的字段进行替换
                sourceAsMap.put("introduce", n_introduce);
            }
            list.add(sourceAsMap);
        }

        return list;
    }
}
